<template>
    <div class="list-box">
        <div class="pannel-title pannel-between">
            <div>管理员列表</div>
            <a-button class="pannel-btn" size="small" type="primary" shape="round" @click="addRole()">
                <PlusCircleFilled />
                新增角色
            </a-button>
        </div>
    </div>
	<div class="role-option">
		<div class="role-info">
			<div class="role-option-title">基本信息</div>
			<a-form style="margin-top:20px;" ref="form1" :model="formState" :rules="rules" :labelCol="{span:6,offset:0}">
				<a-form-item label="角色名称" name="name">
					<a-input
						v-model:value="formState.name"
						placeholder="角色名称"
					/>
				</a-form-item>
				<a-form-item label="角色描述" name="memo">
					<a-input
						v-model:value="formState.memo"
						placeholder="请输入角色描述"
					/>
				</a-form-item>
				<a-form-item label="状态" name="status">
					<a-select v-model:value="formState.status">
						<a-select-option value="Y">启用</a-select-option>
						<a-select-option value="N">禁用</a-select-option>
					</a-select>
				</a-form-item>
			</a-form>
		</div>
		<div class="role-menu">
			<div class="role-option-title">权限分配</div>
			<a-table
                :row-key="(record) => record.id"
                :data-source="dataSource"
                :pagination="false"
                :loading="isLoading"
				:expandIconColumnIndex="1"
            >
				<a-table-column width="60px" key="checked" data-index="checked">
					<template #title><a-checkbox v-model:checked="checkedAll" :indeterminate="checkedAllHalf" @change="checkedAllRow"></a-checkbox></template>
					<template #default="{ record }">
						<a-checkbox v-if="record.position === 2" v-model:checked="record.checked" @change="checkedRow($event,record)"></a-checkbox>
						<a-checkbox v-else v-model:checked="record.checked" :indeterminate="record.checkedHalf" @change="checkedRow($event,record)"></a-checkbox>
					</template>
				</a-table-column>
				<a-table-column key="name" title="菜单名称" data-index="name" />
				<a-table-column key="front_path" title="菜单路径" data-index="front_path" />
				<a-table-column key="path" title="菜单权限" data-index="path" />
            </a-table>
		</div>
	</div>
	<div class="update-btn">
		<a-button type="default" shape="round" @click="back()">返回</a-button>
		<a-button type="primary" shape="round" @click="confirm()">保存</a-button>
	</div>
</template>
<script>
import { PlusCircleFilled } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { ref } from "@vue/reactivity";
import { message, Table,Button,Form,Input,Select, Checkbox} from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
export default {
    components: {
        PlusCircleFilled,
        ATable: Table,
		ATableColumn:Table.Column,
		AButton:Button,
		AForm:Form,
		AFormItem:Form.Item,
		ASelect:Select,
		ASelectOption:Select.Option,
		AInput:Input,
		ACheckbox:Checkbox
    },
    setup() {
        const store = useStore();
        //text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
        store.dispatch("setBreadcrumb", {
            text: "系统设置 / 角色管理 / 角色权限设置",
            isBack: false,
        });
        const dataSource = ref([]);
		const formState = ref({
			id:"",
            name:"",
            memo:"",
            status:"",
        });
        return {
            dataSource,
            formState,
            isLoading: ref(false),
			checkedAll:ref(false),
			checkedAllHalf:ref(false),
        };
    },
    data() {
        return {
            rules: {
                name: {
                    required: true,
                    message: "不能为空",
                    trigger: "blur",
                },
                status: {
                    required: true,
                    message: "不能为空",
                    trigger: "change",
                },
            },
			roleId:null,
			roleData:{},
			menuList:[],
			selectedMenu:[]
        };
    },
    mounted() {
		this.roleId = this.$route.query.id;
		this.roleData = JSON.parse(sessionStorage.getItem("editRole"));
		const {id,name,memo,status} = this.roleData;
		this.formState = {id,name,memo,status};
		this.isLoading = true;
		Promise.all([httpRequest.post("checkedManagerRoles",{id:this.roleId}),httpRequest.post("getManagerPagePaths", {})]).then(res=>{
			this.menuList = res[1].data;
			this.selectedMenu = res[0].data;
			this.dataSource = this.getMenuByTree(res[1].data);
		}).finally(() => {
			this.isLoading = false;
		});
    },
    methods: {
		getMenuByTree(list){
			const array = list.filter(e=>e.parent_id === 0);
			const obj = {};
			list.forEach(e=>{
				obj[e.id] = e;
			});
			list.forEach(e=>{
				if(e.parent_id !== 0){
					e.$parent = obj[e.parent_id];
					if(obj[e.parent_id].children){
						obj[e.parent_id].children.push(e);
					}else{
						obj[e.parent_id].children=[e];
					}
				}
			});
			this.selectedMenu.forEach(e=>{
				if(e.id){
					obj[e.id].checked = true;
				}
			})
			return array;
		},
		//行勾选事件
		checkedRow(e,item){
			const checked = e.target.checked;
			//处理子节点选中状态
			if(item.children){
				item.children.forEach(event=>{
					event.checked = checked;
					if(event.children){
						event.children.forEach(a=>a.checked = checked);
					}
				})
			}
			//处理父节点选中状态
			if(item.$parent){
				checked ? this.setParentChecked(item.$parent) : this.setParentUnChecked(item.$parent);
			}
			//处理表格全选勾选框选中状态
			const len = this.menuList.filter(e=>e.checked).length;
			if(len === this.menuList.length){
				this.checkedAll = true;
				this.checkedAllHalf = false;
			}else if(len < this.menuList.length && len >0){
				this.checkedAll = true;
				this.checkedAllHalf = true;
			}else{
				this.checkedAll = false;
				this.checkedAllHalf = false;
			}
		},
		//选中时处理父节点状态
		setParentChecked(parent){
			parent.checked = true;
			const len = parent.children.filter(e=>e.checked).length;
			parent.checkedHalf = parent.children.length === len ? false : true;
			if(parent.$parent){
				this.setParentChecked(parent.$parent);
			}
		},
		//取消选中时处理父节点状态
		setParentUnChecked(parent){
			const len = parent.children.filter(e=>e.checked).length;
			if(len > 0){
				parent.checked = true;
				parent.checkedHalf = true;
			}else{
				parent.checked = false;
				parent.checkedHalf = false;
			}
			if(parent.$parent){
				this.setParentUnChecked(parent.$parent);
			}
		},
		//表格头全选/取消全选事件
		checkedAllRow(e){
			const checked = e.target.checked;
			this.menuList.forEach(e=>e.checked = checked);
		},
		back(){
			this.$router.back();
		},
        confirm() {
            this.$refs.form1.validate().then(()=>{
				const pageIds = this.menuList.filter(e=>e.checked).map(e=>e.id).join(",");
                httpRequest.post("editManagerRole",{...this.formState,pageIds}).then(() => {
                    message.success("保存成功");
                });
            })
        },
    },
};
</script>
<style lang="less" scoped>
.role-option{
	margin-top: 20px;
	display: flex;
	justify-content: space-between;
	align-items: stretch;
	.role-info{
		width: 30%;
		margin-right: 10px;
		background: #fff;
		padding:20px;
		padding-top: 0;
	}
	.role-menu{
		width: calc(70% - 10px);
		background: #fff;
		padding:20px;
		padding-top: 0;
	}
	.role-option-title{
		height: 42px;
		line-height: 43px;
		border-bottom: 1px solid #dcdcdc;
		font-size: 16px;
		font-weight: bold;
		text-align: left;
		margin-bottom: 10px;
		padding-top: 2px;
	}
}
.update-btn{
	margin-top: 30px;
	button{
		padding-left: 30px;
		padding-right: 30px;
		margin:0 20px;
	}
}
</style>
